package com.globallogic.week3.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.globallogic.week3.util.AuthUserHandler;

@WebFilter(urlPatterns="/*")
public class AuthCheckFilter implements Filter{
	private static final Logger log = Logger.getLogger(AuthCheckFilter.class);
	private List<String> urlsForAuth = null;
	private List<String> urlsForNotAuth = null;

	@Override
	public void destroy() {
		urlsForAuth.clear();
		urlsForNotAuth.clear();
		urlsForAuth = null;
		urlsForNotAuth = null;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		
			log.info("Start filtering..");
			
			HttpServletRequest httpServletRequest = (HttpServletRequest) req;
			HttpSession session = httpServletRequest.getSession();
			AuthUserHandler authUserHandler = (AuthUserHandler) req.getServletContext().getAttribute("authUserHandler");

			log.info("Servlet Context Path: " + httpServletRequest.getContextPath());
			log.info("Servlet Path: " + httpServletRequest.getServletPath());
			
			Object value = session.getAttribute("isAuth");
			if(value != null){
				String isAuth = (String) session.getAttribute("isAuth");
				
				if(authUserHandler.contains(isAuth)
						&& urlsForAuth.contains(httpServletRequest.getServletPath())){
					req.setAttribute("operationStatus", "You are registered and authentificated!");
					req.getRequestDispatcher("notify.jsp").forward(req, resp);
				}
			}else if (urlsForNotAuth.contains(httpServletRequest.getServletPath())) {
				req.setAttribute("operationStatus", "You are not registered and authentificated! Please, register!");
				req.getRequestDispatcher("notify.jsp").forward(req, resp);
			}
			chain.doFilter(req, resp);
			log.info("Start filtering..");
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		urlsForAuth = new ArrayList<>();
		urlsForAuth.add("/login");
		urlsForAuth.add("/login.jsp");
		urlsForAuth.add("/register");
		urlsForAuth.add("/registration.jsp");
		
		urlsForNotAuth = new ArrayList<>();
		urlsForNotAuth.add("/secured_page.jsp");
	}

}
